<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0;">
      <el-form :inline="true" :model="query">
        <el-form-item>
          <el-input v-model="query.username" placeholder="部门名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="add">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain @click="importData">导入数据</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" plain @click="exportData">导出数据</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <!--列表-->
    <el-table border :data="tableData" highlight-current-row v-loading="listLoading" @selection-change="selectChange"
              style="width: 100%;">
      <el-table-column type="selection">
      </el-table-column>
      <el-table-column type="index">
      </el-table-column>
      <el-table-column prop="username" label="用户名">
      </el-table-column>
      <el-table-column prop="email" label="联系邮箱">
      </el-table-column>
      <el-table-column prop="age" label="年龄">
      </el-table-column>
      <el-table-column prop="headImage" label="头像">
        <template slot-scope="scope">
          <img :src="scope.row.headImage" style="width: 50px;height: 50px;border-radius: 50%;" alt="加载失败">
        </template>
      </el-table-column>
      <el-table-column prop="department.name" label="所属部门">
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template slot-scope="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.selection.length===0">批量删除</el-button>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="float:right;">
      </el-pagination>
    </el-col>
    <el-dialog :title="title" :visible.sync="dialogVisible" @close="dialogClose" width="30%">
      <el-form :model="emp" label-width="80px" :rules="rules" ref="rules">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="emp.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="emp.email"></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="emp.age"></el-input>
        </el-form-item>
        <el-form-item label="所属部门">
          <el-select v-model="emp.departmentId" placeholder="请选择">
            <el-option
                v-for="item in deptList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogClose">取消</el-button>
          <el-button type="primary" @click="submit" :loading="saveLoading">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
        title="导入员工数据"
        :visible.sync="uploadDialog"
        width="30%"
        @close="closeUpload">
      <el-upload
          class="upload-demo"
          ref="upload"
          action=""
          :http-request="http"
          :file-list="fileList"
          :limit="1"
          name="file"
          :headers="token"
          :on-success="handleSuccess"
          :auto-upload="false">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <div slot="tip" class="el-upload__tip">只能上传Excel文件，且不超过10Mb</div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadDialog = false">取 消</el-button>
        <el-button type="success" @click="submitUpload">上 传</el-button>
      </span>
    </el-dialog>
  </section>
</template>

<script>
export default {
  name: "Employee",
  data() {
    return {
      query: {
        username: ''
      },
      currentPage: 1,
      pageSize: 5,
      total: 0,
      tableData: [],
      fileList: [],
      listLoading: false,
      selection: [],
      dialogVisible: false,
      uploadDialog: false,
      title: '',
      token: {
        "TOKEN": localStorage.getItem('token')
      },
      emp: {},
      rules: {
        username: [
          {required: true, message: '请输入部门名称', trigger: 'blur'}
        ]
      },
      saveLoading: false,
      deptList: [],
    }
  },
  mounted() {
    this.getEmpList();
  },
  methods: {
    http(param) {
      let file = param.file;
      let fileObj = new FormData();
      fileObj.append('file', file);
      this.$axios.post('/emp/import', fileObj, {
        responseType: 'arraybuffer',
        headers: {
          "Content-Type": "multipart/form-data"
        }
      })
          .then(res => {
            if (res.headers['code'] === "0") {
              const content = res.data
              let link = document.createElement("a");
              const blogw = new Blob([content], {type: "application/vnd.ms-excel;charset=utf-8"});
              let objectUrl = window.URL.createObjectURL(blogw);    //创建一个新的url对象
              link.href = objectUrl;
              link.download = 'ss.xls';    //  下载的时候自定义的文件名
              link.click();
              window.URL.revokeObjectURL(objectUrl);   //为了更好地性能和内存使用状况，应该在适当的时候释放url.
            } else {
              // 上传成功
              this.handleSuccess()
            }
          })
          .catch(error => {
            console.error('文件上传失败:', error);
            this.$message.error('文件上传失败，请重试');
          });
    },
    exportData() {
      this.$axios.get('/emp/export', {
        responseType: 'blob',
        params: {
          name: this.query.username
        }
      })
          .then(response => {
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const a = document.createElement('a');
            a.href = url;
            a.download = 'testExport.xls';
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
          });
    },
    handleSuccess() {
      this.$message.success("导入成功!");
      this.uploadDialog = false;
      this.fileList = [];
      this.getEmpList();
    },
    importData() {
      this.uploadDialog = true;
    },
    closeUpload() {
      this.fileList = [];
      this.$refs.upload.clearFiles();
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    batchRemove() {
      this.$axios.patch('/emp', this.selection)
          .then(res => {
            if (res.data.code === 1) {
              this.$message.success("删除成功!");
              this.getEmpList();
            } else {
              this.$message.error(res.data.msg || '删除失败');
            }
          })
    },
    getDeptList() {
      this.listLoading = true;
      this.$axios.get('/dept')
          .then(res => {
            this.listLoading = false;
            if (res.data.code === 1) {
              this.deptList = res.data.data;
            } else {
              this.$message.error(res.data.msg);
            }
          })
    },
    search() {
      this.currentPage = 1;
      this.getEmpList();
    },
    getEmpList() {
      this.$axios.post('/emp', {
        username: this.query.username,
        page: this.currentPage,
        pageSize: this.pageSize
      }).then(res => {
        if (res.data.code === 1) {
          this.tableData = res.data.data.rows;
          this.total = res.data.data.total;
        } else {
          this.$message.error(res.data.msg);
        }
      })
    },
    add() {
      this.getDeptList();
      this.title = '新增员工';
      this.dialogVisible = true;
    },
    submit() {
      this.$refs.rules.validate(valid => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {type: 'warning'}).then(() => {
            this.saveLoading = true;
            this.$axios.put('/emp', this.emp).then((res) => {
              this.saveLoading = false;
              if (res.data.code === 1) {
                this.$message.success("提交成功")
              } else {
                this.$message.error(res.data.msg || '提交失败');
              }
              this.$refs['rules'].resetFields();
              this.dialogVisible = false;
              this.getEmpList();
            });
          });
        }
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getEmpList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getEmpList();
    },
    selectChange(val) {
      this.selection = val.map(item => item.id);
    },
    dialogClose() {
      this.emp = {};
      this.dialogVisible = false;
    },
    handleEdit(row) {
      this.getDeptList();
      this.title = '编辑部门';
      this.dialogVisible = true;
      this.emp = {...row};
    },
    handleDel(id) {
      this.$confirm('确认删除该记录吗？', '提示', {type: 'warning'}).then(() => {
        this.listLoading = true;
        this.$axios.delete('/emp/' + id).then((res) => {
          this.listLoading = false;
          if (res.data.code === 1) {
            this.$message.success("删除成功")
            //如果当前页数据被删除完了，则自动切换到上一页
            if (this.tableData.length === 1 && this.currentPage > 1) {
              this.currentPage--;
            }
            this.getEmpList();
          } else {
            this.$message.error(res.data.msg || '删除失败');
          }
        })
      })
    }
  }
}
</script>

<style scoped>

</style>